/**
 * 
 */
package org.melord.cap;

import java.io.IOException;

import jpcap.JpcapCaptor;
import jpcap.NetworkInterface;
import jpcap.PacketReceiver;
import jpcap.packet.Packet;

/**
 * @author melord
 * 
 */
public class Capture {
	public NetworkInterface[] getDevices() {
		NetworkInterface[] devices = JpcapCaptor.getDeviceList();
		return devices;
	}

	JpcapCaptor captor;
	Thread thread;
	private PacketReceiver mReceiver;
	private NetworkInterface device;

	public void startCapture() {
		if (device == null || mReceiver == null) {
			return;
		}
		stop();
		thread = new Thread() {
			@Override
			public void run() {
				try {
					System.out.println("start capture");
					captor = JpcapCaptor.openDevice(device, 1514, true, 20);
					captor.setFilter("tcp and ip", true);
					captor.loopPacket(-1, mReceiver);
				} catch (IOException e) {
					e.printStackTrace();
					captor = null;
					System.out.println(captor);
				}
			}
		};
		thread.start();
	}

	public void stop() {
		if (thread != null) {
			if (captor != null) {
				captor.breakLoop();
				captor.close();
				System.out.println("stop capture");
			}
			if (!thread.isInterrupted()) {
				thread.interrupt();
				thread = null;
			}

		}
	}

	public void setDevice(NetworkInterface device) {
		this.device = device;
		startCapture();
	}

	public void setReceiver(PacketReceiver receiver) {
		mReceiver = receiver;
	}

	public static void main(String[] args) {
		Capture cap = new Capture();
		cap.setReceiver(new PacketReceiver() {

			@Override
			public void receivePacket(Packet arg0) {
				// TODO Auto-generated method stub

			}
		});
		cap.setDevice(cap.getDevices()[0]);

	}
}
